import { CydonElement, define } from 'cydon'
import { onHashChange } from '../utils'
import { API } from '../api'
import { aliases } from '@cydon/ui/src/dialog'

/** 判断链接是否激活 */
const isActive = (href: string) =>
	location.href.endsWith(href)

aliases.set('reg', 'login')

/** 导航栏 */
@define('nav-bar')
export class NavBar extends CydonElement {
	/** 当前用户名 */
	name = ''

	connectedCallback() {
		onHashChange(() => {
			// 更新导航栏链接的激活状态
			for (const a of this.querySelectorAll('a:link')) {
				a.classList.toggle('active', isActive(a.getAttribute('href')!))
			}
		})
		// 获取用户信息
		API.auth(getToken()).then(([user, token]) => {
			if (user) {
				this.data.name = user.name
			}
			if (token)
				saveToken(token, sessionStorage)
		}, () => {
			if (API.state == WebSocket.OPEN) {
				removeToken()
			}
		})
		this.addEventListener('user-login', (e: CustomEvent) => {
			const { name, token, keep } = e.detail
			location.hash = ''
			this.data.name = name
			saveToken(token, keep ? localStorage : sessionStorage)
		})
		super.connectedCallback()
	}

	/** 查看/编辑令牌 */
	showToken() {
		const token = prompt("令牌", getToken())
		if (token)
			saveToken(token)
	}

	/** 自定义API地址 */
	setAPI() {
		const url = prompt("自定义API地址（留空则为默认地址）", localStorage.getItem('hostURL') || '')
		if (url) {
			localStorage.setItem('hostURL', url)
			location.reload()
		}
	}

	/** 登出 */
	logout() {
		removeToken()
		location.reload()
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'nav-bar': NavBar
	}
}

/** 获取 token，若为空则表示未登录 */
export function getToken() {
	return sessionStorage.getItem('token') ||
		localStorage.getItem('token') ||
		''
}

/** 设置 token */
function saveToken(token: string, storage = localStorage) {
	storage.setItem('token', token)
}

/** 移除 token */
function removeToken() {
	sessionStorage.removeItem('token')
	localStorage.removeItem('token')
}
